package com.timothy.asset.util;

import org.apache.log4j.Logger;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;

/**
 * Created with IntelliJ IDEA.
 * User: qtang
 * Date: 9/21/12
 * Time: 1:48 PM
 * To change this template use File | Settings | File Templates.
 */
public class MailUtil {
    private static Logger logger = Logger.getLogger(MailUtil.class.getName());



    private void sendEmail(String from, String host, String toAddress, String ccAddress, String subject, String body, File file) {
        logger.debug("============= Begin send mail =============");
        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", host);
            Session session = Session.getDefaultInstance(props, null);
            try {
                Message msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress(from));

                //process To addresses
                StringTokenizer st = new StringTokenizer(toAddress, ";");
                ArrayList<InternetAddress> toAddressList = new ArrayList<InternetAddress>();
                while (st.hasMoreTokens()) {
                    String address = st.nextToken();
                    InternetAddress add = new InternetAddress(address);
                    toAddressList.add(add);
                }
                InternetAddress[] toAddList = new InternetAddress[toAddressList.size()];
                toAddressList.toArray(toAddList);
                msg.setRecipients(javax.mail.Message.RecipientType.TO, toAddList);

                //process CC addresses
                if (ccAddress != null && !ccAddress.equals("")) {
                    st = new StringTokenizer(ccAddress, ";");
                    ArrayList<InternetAddress> ccAddressList = new ArrayList<InternetAddress>();
                    while (st.hasMoreTokens()) {
                        String address = st.nextToken();
                        InternetAddress add = new InternetAddress(address);
                        ccAddressList.add(add);
                    }
                    InternetAddress[] ccAddList = new InternetAddress[ccAddressList.size()];
                    ccAddressList.toArray(ccAddList);
                    msg.setRecipients(javax.mail.Message.RecipientType.CC, ccAddList);
                }

                //process subject
                msg.setSubject(subject);
                //process date
                msg.setSentDate(new java.util.Date());

                //process body
                Multipart mp = new MimeMultipart();
                MimeBodyPart bodyPart = new MimeBodyPart();
                bodyPart.setText(body);
                mp.addBodyPart(bodyPart);

                //process attachment
                if (file != null) {
                    MimeBodyPart attachment = new MimeBodyPart();
                    // attach the file to the message
                    String filename = "./" + file;
                    FileDataSource fds = new FileDataSource(filename);
                    attachment.setDataHandler(new DataHandler(fds));
                    attachment.setFileName(fds.getName());
                    mp.addBodyPart(attachment);
                }

                msg.setContent(mp);
                Transport.send(msg);
            } catch (MessagingException mex) {
                logger.error("sendEmail - Exception handling in AgDriver.java" + mex.getMessage());
                Exception ex = mex;
                do {
                    if (ex instanceof SendFailedException) {
                        SendFailedException sfex = (SendFailedException) ex;
                        javax.mail.Address invalid[] = sfex.getInvalidAddresses();
                        if (invalid != null) {
                            int invalidCount = invalid.length;
                            logger.error("sendEmail - Invalid Addresses");
                            for (int i = 0; i < invalidCount; i++) {
                                logger.error("sendEmail - " + invalid[i]);
                            }
                        }
                    }
                } while ((ex = ((MessagingException) ex).getNextException()) != null);
            }
        } catch (Exception ex) {
            logger.error("sendEmail - " + ex.getMessage());
        }
        logger.debug("============= End send mail =============");
    }
}
